%%%-------------------------------------------------------------------
%% @doc mqeg public API
%% @end
%%%-------------------------------------------------------------------

-module(mqeg_app).

-behaviour(application).

-include("debug.hrl").
-include_lib("amqp_client/include/amqp_client.hrl").

-export([start/2, stop/1]).

start(_StartType, _StartArgs) ->
    ok = mqeg_misc:init_singleton(),
    ok = start_rabbitmq(),
    ok = start_web(),

    mqeg_sup:start_link().

stop(_State) ->
    ok.


%% internal functions
%% -----------------------------------------------------------------------------
start_rabbitmq() ->
    {ok, ConnCfg}   = application:get_env(mqeg, connection),
    % {ok, ExcCfg}    = application:get_env(mqeg, exchange),
    % {ok, QueCfg}    = application:get_env(mqeg, queue),
    % {ok, MsgCfg}    = application:get_env(mqeg, message),
    
    Params = #amqp_params_network{ username     = proplists:get_value(username,     ConnCfg)
                                 , password     = proplists:get_value(password,     ConnCfg)
                                 , host         = proplists:get_value(host,         ConnCfg)
                                 , port         = proplists:get_value(port,         ConnCfg)
                                 , virtual_host = proplists:get_value(virtual_host, ConnCfg)
                                 },
    {ok, Connection} = amqp_connection:start(Params),
    mqeg_misc:set_singleton(connection, Connection),
    ok.

%% -----------------------------------------------------------------------------
start_web() ->
    {ok, WebCfg}   = application:get_env(mqeg, web),
    TransOpts = get_trans_opts(WebCfg),
    ProtoOpts = get_proto_opts(WebCfg),

    {ok, _} = cowboy:start_clear(?MODULE, TransOpts, ProtoOpts),
    ok.

get_trans_opts(Config) ->
    #{ max_connections  => proplists:get_value(max_connections, Config)
     , num_acceptors    => proplists:get_value(num_acceptors,   Config)
     , num_conns_sups   => proplists:get_value(num_conns_sups,  Config)
     , socket_opts      => [{port, proplists:get_value(port,    Config)}]
     }.

get_proto_opts(_Config) ->
    Dispatch = init_dispatch(),
    %% 大量路由可以使用优化
    %% persistent_term:put ( my_app_dispatch , Dispatch ),
    #{ env => #{ dispatch => Dispatch }
     }.

%% 
init_dispatch() ->
    Host1 = {'_', init_path1()},
    Router = [ Host1 ],
    cowboy_router:compile(Router).

init_path1() ->
    [ {"/",                     cowboy_static,      {priv_file, mqeg, "/index.html"}}
    , {"/api/publish/[...]",    mqeg_api_publish,  []}
    , {"/api/consum/[...]",     mqeg_api_consum,   []}
    , {"/[...]",                cowboy_static,      {priv_dir,  mqeg, ""}}
    ].